import { UploadOutlined } from "@ant-design/icons";
import { Button, Input, Upload, message, Modal } from "antd";
import { useState } from "react";
import CryptoJS from "crypto-js";

export default () => {
    const [fileName, setFileName] = useState("");
    const [fileHash, setFileHash] = useState({ sha256: "", md5: "" });

    const props = {
        beforeUpload: (file) => {
            if (typeof FileReader == "undifined") {
                //判断浏览器是否支持filereader
                message.warn("抱歉，你的浏览器不支持 FileReader");
                return false;
            }
            setFileName(file.name);
            if (file.size > 1024 * 1024 * 30) {
                message.warn("抱歉，文件的大小不能超过30M");
                return false;
            }

            const modal = Modal.info({ content: "正在计算文件HASH...", okButtonProps: { loading: true } });

            setTimeout(() => {
                var reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = function (e) {
                    var wordArray = CryptoJS.lib.WordArray.create(this.result);
                    setFileHash({ sha256: CryptoJS.SHA256(wordArray).toString(), md5: CryptoJS.MD5(wordArray).toString() });
                    modal.destroy();
                };
            }, 1000);

            return false;
        },
        fileList: [],
    };

    return (
        <div>
            <Upload {...props}>
                <Button icon={<UploadOutlined />}>选择文件</Button>
                <span style={{ paddingLeft: 20 }}>{fileName}</span>
            </Upload>
            文件大小在30M以内！
            <div style={{ marginTop: 10 }}>
                文件HASH：（SHA256）
                <Input.TextArea value={fileHash.sha256} style={{ width: "100%", height: 100 }} />
            </div>
            <div style={{ marginTop: 10 }}>
                文件HASH：（MD5）
                <Input.TextArea value={fileHash.md5} style={{ width: "100%", height: 100 }} />
            </div>
        </div>
    );
};
